/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import com.railway.utils.CustomTableModel;
import com.railway.utils.CustomScrollBarUI;
import com.railway.utils.ImageFilter;
import com.railway.utils.ImagePreview;
import com.railway.utils.MultiLineTableCellRenderer;
import com.railway.utils.QRDecoderPanel;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import org.apache.commons.codec.binary.Base64;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Kenny
 */
public class PointRedemptionPanel extends javax.swing.JPanel {

    Image imgArrow = new ImageIcon(this.getClass().getResource("/com/railway/image/arrow.png")).getImage();
    Image imgArrow180 = new ImageIcon(this.getClass().getResource("/com/railway/image/arrow-180.png")).getImage();
    private DecimalFormat dcFormat = new DecimalFormat("00");
    private ArrayList<String> colName;
    private ArrayList<ArrayList<Object>> rowData;
    private JSONObject json;
    private JSONArray jsonArray;
    private CustomTableModel ctmModel;
    private CardLayout cl;
    private Map<String, Object> imageData;
    private String itemCode;
    private String refNo;
    private QRDecoderPanel decoder = null;
    private boolean isSouvenir = false;

    /**
     * Creates new form PointRedemptionPanel
     */
    public PointRedemptionPanel() {
        initComponents();
        cl = (CardLayout) jpItemCard.getLayout();
        populateTableData();
    }

    private void populateTableData() {
        new Thread() {
            @Override
            public void run() {
                colName = new ArrayList<>();
                colName.add("<html>Item<br/>Code");
                colName.add("<html>Item<br/>Name");
                colName.add("<html>Point<br/>Needed");
                colName.add("<html>Value<br/>&nbsp;");
                colName.add("<html>Item<br/>Type");
                colName.add("itemimage");
                String data = RestServer.httpGet("redeemableitem", "");
                try {
                    json = new JSONObject(data);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        rowData = new ArrayList<>();
                        int status = json.getInt("status");
                        if (status == 200) {
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                ArrayList<Object> temp = new ArrayList<>();
                                temp.add(jsonArray.getJSONObject(i).get("itemCode"));
                                temp.add(jsonArray.getJSONObject(i).get("itemName"));
                                temp.add(jsonArray.getJSONObject(i).get("pointRequired"));
                                temp.add(jsonArray.getJSONObject(i).get("value"));
                                temp.add(jsonArray.getJSONObject(i).get("itemType"));
                                temp.add(jsonArray.getJSONObject(i).get("itemImage"));
                                rowData.add(temp);
                            }
                            ctmModel = new CustomTableModel(colName, rowData);
                            jtbRedeemItem.setModel(ctmModel);
                            jtbRedeemItem.removeColumn(jtbRedeemItem.getColumnModel().getColumn(5));
                            jtbRedeemItem.getColumnModel().getColumn(1).setCellRenderer(new MultiLineTableCellRenderer());
                            jtbRedeemItem.repaint();
                        }
                    } else {
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                    }
                } catch (JSONException ex) {
                }
            }
        }.start();
    }

    private void generateByteDataFromImageFile(File file) {
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, file.getName().substring(file.getName().lastIndexOf(".") + 1), baos);
            byte[] imageByte = baos.toByteArray();
            String encoded = Base64.encodeBase64String(imageByte);
            imageData = new HashMap<>();
            imageData.put("imagedata", encoded);
            imageData.put("imagename", file.getName());
        } catch (IOException | IllegalArgumentException ex) {
            Toast.makeText(this, "This is not a valid image file.", Toast.LENGTH_SHORT).display();
        }
    }

    private String generateItemCode() {
        String type = jcbxAItemType.getSelectedItem().toString();
        String temp;
        String itemcode = null;
        switch (type) {
            case "Coupon":
                temp = "CPNP";
                itemcode = temp.concat(dcFormat.format(Double.parseDouble(jspiAValue.getValue().toString())));
                break;
            case "Credit":
                temp = "CRDC";
                itemcode = temp.concat(dcFormat.format(Double.parseDouble(jspiAValue.getValue().toString())));
                break;
            case "Souvenir":
                temp = "SVR";
                itemcode = temp.concat(jtfAItemName.getText().trim().substring(jtfAItemName.getText().trim().lastIndexOf(" ") + 1).toUpperCase());
                break;
        }
        return itemcode;
    }

    private ImageIcon getImageFile(String url, boolean isUrl) {
        Image img;
        BufferedImage bfImg = null;
        try {
            if (isUrl) {
                String serverurl = "http://localhost/RailwayWeb/";
                img = new ImageIcon(new URL(serverurl + url)).getImage();
            } else {
                img = ImageIO.read(new File(url));
            }
            bfImg = new BufferedImage(jlblImage.getWidth(), jlblImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = bfImg.createGraphics();
            g2d.drawImage(img, 0, 0, jlblImage.getWidth(), jlblImage.getHeight(), this);
            g2d.dispose();
        } catch (MalformedURLException ex) {
            Logger.getLogger(PointRedemptionPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PointRedemptionPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ImageIcon(bfImg);
    }

    private void checkItemCode(String refNo) {
        String result = RestServer.httpGet("redeemeditem", refNo);
        try {
            json = new JSONObject(result);
            boolean error = json.optBoolean("error");
            if (!error) {
                int statuscode = json.getInt("status");
                if (statuscode == 200) {
                    jlblScanResult.setText("This is a valid item code.");
                    this.refNo = refNo;
                    jbtRedeem.setEnabled(true);
                } else {
                    jlblScanResult.setText("This item code has already been used.");
                    jbtRedeem.setEnabled(false);
                }
            } else {
                Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
            }
        } catch (JSONException ex) {
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jfcImageChooser = new javax.swing.JFileChooser();
        jpAddArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpRedemption = new javax.swing.JPanel();
        jlblItems = new javax.swing.JLabel();
        jsprItems = new javax.swing.JSeparator();
        jspItemScroller = new javax.swing.JScrollPane();
        jtbRedeemItem = new javax.swing.JTable();
        jpItemContent = new javax.swing.JPanel();
        jbtAddItem = new javax.swing.JButton();
        jbtModifyItem = new javax.swing.JButton();
        jbtRedeemItem = new javax.swing.JButton();
        jpItemCard = new javax.swing.JPanel();
        jpNullCard = new javax.swing.JPanel();
        jpAddItemCard = new javax.swing.JPanel();
        jpAddItemArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpAddItem = new javax.swing.JPanel();
        jlblAItemType = new javax.swing.JLabel();
        jcbxAItemType = new javax.swing.JComboBox();
        jlblAItemName = new javax.swing.JLabel();
        jtfAItemName = new javax.swing.JTextField();
        jlblAPoint = new javax.swing.JLabel();
        jspiAPoint = new javax.swing.JSpinner();
        jlblAValue = new javax.swing.JLabel();
        jspiAValue = new javax.swing.JSpinner();
        jbtAReset = new javax.swing.JButton();
        jbtASubmit = new javax.swing.JButton();
        jlblAImage = new javax.swing.JLabel();
        jtfImagePath = new javax.swing.JTextField();
        jbtChoose = new javax.swing.JButton();
        jpModifyItemCard = new javax.swing.JPanel();
        jpModifyItemArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpModifyItem = new javax.swing.JPanel();
        jpImagePopup = new javax.swing.JPanel();
        jpImgArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow180, 0,-20, getWidth(), imgArrow180.getHeight(this), this);
            }
        };
        jpImage = new javax.swing.JPanel();
        jlblImage = new javax.swing.JLabel();
        jlblMItemType = new javax.swing.JLabel();
        jlblMItemName = new javax.swing.JLabel();
        jlblMPoint = new javax.swing.JLabel();
        jtfMItemName = new javax.swing.JTextField();
        jspiMPoint = new javax.swing.JSpinner();
        jlblMValue = new javax.swing.JLabel();
        jspiMValue = new javax.swing.JSpinner();
        jbtRemove = new javax.swing.JButton();
        jbtMSubmit = new javax.swing.JButton();
        jlblMImage = new javax.swing.JLabel();
        jbtChooseAnother = new javax.swing.JButton();
        jbtViewImage = new javax.swing.JButton();
        jtfMItemType = new javax.swing.JTextField();
        jpRedeemCard = new javax.swing.JPanel();
        jpRedeemItemArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpRedeemItem = new javax.swing.JPanel();
        jpScanner = new javax.swing.JPanel();
        jlblScanResult = new javax.swing.JLabel();
        jbtRedeem = new javax.swing.JButton();

        jfcImageChooser.addChoosableFileFilter(new ImageFilter());
        jfcImageChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
        jfcImageChooser.setAccessory(new ImagePreview(jfcImageChooser));

        setBackground(new java.awt.Color(255, 255, 255));
        setPreferredSize(new java.awt.Dimension(860, 375));
        setLayout(null);

        jpAddArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpAddArrowLayout = new javax.swing.GroupLayout(jpAddArrow);
        jpAddArrow.setLayout(jpAddArrowLayout);
        jpAddArrowLayout.setHorizontalGroup(
            jpAddArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 180, Short.MAX_VALUE)
        );
        jpAddArrowLayout.setVerticalGroup(
            jpAddArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        add(jpAddArrow);
        jpAddArrow.setBounds(670, 0, 180, 10);

        jpRedemption.setBackground(new java.awt.Color(255, 255, 255));
        jpRedemption.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpRedemption.setLayout(null);

        jlblItems.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlblItems.setText("REDEEMABLE ITEMS");
        jpRedemption.add(jlblItems);
        jlblItems.setBounds(465, 0, 380, 20);
        jpRedemption.add(jsprItems);
        jsprItems.setBounds(465, 20, 380, 5);

        jspItemScroller.getVerticalScrollBar().setUI(new CustomScrollBarUI());

        jtbRedeemItem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jspItemScroller.setViewportView(jtbRedeemItem);

        jpRedemption.add(jspItemScroller);
        jspItemScroller.setBounds(465, 25, 380, 330);

        jpItemContent.setBackground(new java.awt.Color(255, 255, 255));
        jpItemContent.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpItemContent.setLayout(null);

        jbtAddItem.setBackground(new java.awt.Color(155, 89, 182));
        jbtAddItem.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtAddItem.setForeground(new java.awt.Color(255, 255, 255));
        jbtAddItem.setText("Add Item");
        jbtAddItem.setFocusPainted(false);
        jbtAddItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAddItemActionPerformed(evt);
            }
        });
        jpItemContent.add(jbtAddItem);
        jbtAddItem.setBounds(5, 5, 120, 50);

        jbtModifyItem.setBackground(new java.awt.Color(155, 89, 182));
        jbtModifyItem.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtModifyItem.setForeground(new java.awt.Color(255, 255, 255));
        jbtModifyItem.setText("Modify Item");
        jbtModifyItem.setFocusPainted(false);
        jbtModifyItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtModifyItemActionPerformed(evt);
            }
        });
        jpItemContent.add(jbtModifyItem);
        jbtModifyItem.setBounds(165, 5, 120, 50);

        jbtRedeemItem.setBackground(new java.awt.Color(155, 89, 182));
        jbtRedeemItem.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtRedeemItem.setForeground(new java.awt.Color(255, 255, 255));
        jbtRedeemItem.setText("Redeem Item");
        jbtRedeemItem.setFocusPainted(false);
        jbtRedeemItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtRedeemItemActionPerformed(evt);
            }
        });
        jpItemContent.add(jbtRedeemItem);
        jbtRedeemItem.setBounds(330, 5, 120, 50);

        jpItemCard.setBackground(new java.awt.Color(255, 255, 255));
        jpItemCard.setLayout(new java.awt.CardLayout());

        jpNullCard.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpNullCardLayout = new javax.swing.GroupLayout(jpNullCard);
        jpNullCard.setLayout(jpNullCardLayout);
        jpNullCardLayout.setHorizontalGroup(
            jpNullCardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 445, Short.MAX_VALUE)
        );
        jpNullCardLayout.setVerticalGroup(
            jpNullCardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 290, Short.MAX_VALUE)
        );

        jpItemCard.add(jpNullCard, "nullcard");

        jpAddItemCard.setBackground(new java.awt.Color(255, 255, 255));
        jpAddItemCard.setLayout(null);

        jpAddItemArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpAddItemArrowLayout = new javax.swing.GroupLayout(jpAddItemArrow);
        jpAddItemArrow.setLayout(jpAddItemArrowLayout);
        jpAddItemArrowLayout.setHorizontalGroup(
            jpAddItemArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 120, Short.MAX_VALUE)
        );
        jpAddItemArrowLayout.setVerticalGroup(
            jpAddItemArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpAddItemCard.add(jpAddItemArrow);
        jpAddItemArrow.setBounds(0, 0, 120, 10);

        jpAddItem.setBackground(new java.awt.Color(255, 255, 255));
        jpAddItem.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpAddItem.setLayout(null);

        jlblAItemType.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAItemType.setText("Select Type of Item");
        jpAddItem.add(jlblAItemType);
        jlblAItemType.setBounds(10, 10, 150, 30);

        jcbxAItemType.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jcbxAItemType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Coupon", "Credit", "Souvenir" }));
        jcbxAItemType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbxAItemTypeActionPerformed(evt);
            }
        });
        jpAddItem.add(jcbxAItemType);
        jcbxAItemType.setBounds(160, 10, 270, 30);

        jlblAItemName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAItemName.setText("Item Name");
        jpAddItem.add(jlblAItemName);
        jlblAItemName.setBounds(10, 50, 150, 30);

        jtfAItemName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpAddItem.add(jtfAItemName);
        jtfAItemName.setBounds(160, 50, 270, 30);

        jlblAPoint.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAPoint.setText("Point Required");
        jpAddItem.add(jlblAPoint);
        jlblAPoint.setBounds(10, 90, 150, 30);

        jspiAPoint.setModel(new javax.swing.SpinnerNumberModel(5, 5, 90, 5));
        jpAddItem.add(jspiAPoint);
        jspiAPoint.setBounds(160, 90, 270, 30);

        jlblAValue.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAValue.setText("Value of Item");
        jpAddItem.add(jlblAValue);
        jlblAValue.setBounds(10, 130, 150, 30);

        jspiAValue.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 99.0d, 1.0d));
        jpAddItem.add(jspiAValue);
        jspiAValue.setBounds(160, 130, 270, 30);

        jbtAReset.setBackground(new java.awt.Color(39, 174, 96));
        jbtAReset.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtAReset.setForeground(new java.awt.Color(255, 255, 255));
        jbtAReset.setText("Reset");
        jbtAReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAResetActionPerformed(evt);
            }
        });
        jpAddItem.add(jbtAReset);
        jbtAReset.setBounds(10, 220, 140, 50);

        jbtASubmit.setBackground(new java.awt.Color(39, 174, 96));
        jbtASubmit.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtASubmit.setForeground(new java.awt.Color(255, 255, 255));
        jbtASubmit.setText("Submit");
        jbtASubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtASubmitActionPerformed(evt);
            }
        });
        jpAddItem.add(jbtASubmit);
        jbtASubmit.setBounds(290, 220, 140, 50);

        jlblAImage.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAImage.setText("Select Item Image");
        jpAddItem.add(jlblAImage);
        jlblAImage.setBounds(10, 170, 150, 30);

        jtfImagePath.setEditable(false);
        jpAddItem.add(jtfImagePath);
        jtfImagePath.setBounds(160, 170, 190, 30);

        jbtChoose.setBackground(new java.awt.Color(39, 174, 96));
        jbtChoose.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtChoose.setForeground(new java.awt.Color(255, 255, 255));
        jbtChoose.setText("Choose");
        jbtChoose.setEnabled(false);
        jbtChoose.setFocusPainted(false);
        jbtChoose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtChooseActionPerformed(evt);
            }
        });
        jpAddItem.add(jbtChoose);
        jbtChoose.setBounds(350, 170, 80, 30);

        jpAddItemCard.add(jpAddItem);
        jpAddItem.setBounds(0, 10, 445, 280);

        jpItemCard.add(jpAddItemCard, "addcard");

        jpModifyItemCard.setBackground(new java.awt.Color(255, 255, 255));
        jpModifyItemCard.setLayout(null);

        jpModifyItemArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpModifyItemArrowLayout = new javax.swing.GroupLayout(jpModifyItemArrow);
        jpModifyItemArrow.setLayout(jpModifyItemArrowLayout);
        jpModifyItemArrowLayout.setHorizontalGroup(
            jpModifyItemArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 120, Short.MAX_VALUE)
        );
        jpModifyItemArrowLayout.setVerticalGroup(
            jpModifyItemArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpModifyItemCard.add(jpModifyItemArrow);
        jpModifyItemArrow.setBounds(160, 0, 120, 10);

        jpModifyItem.setBackground(new java.awt.Color(255, 255, 255));
        jpModifyItem.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpModifyItem.setLayout(null);

        jpImagePopup.setBackground(new java.awt.Color(255, 255, 255));
        jpImagePopup.setLayout(null);

        jpImgArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpImgArrowLayout = new javax.swing.GroupLayout(jpImgArrow);
        jpImgArrow.setLayout(jpImgArrowLayout);
        jpImgArrowLayout.setHorizontalGroup(
            jpImgArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 155, Short.MAX_VALUE)
        );
        jpImgArrowLayout.setVerticalGroup(
            jpImgArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpImagePopup.add(jpImgArrow);
        jpImgArrow.setBounds(0, 155, 155, 10);

        jpImage.setBackground(new java.awt.Color(255, 255, 255));
        jpImage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220)));
        jpImage.setLayout(null);

        jlblImage.setBackground(new java.awt.Color(255, 255, 255));
        jlblImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jpImage.add(jlblImage);
        jlblImage.setBounds(1, 1, 153, 153);

        jpImagePopup.add(jpImage);
        jpImage.setBounds(0, 0, 155, 155);

        jpModifyItem.add(jpImagePopup);
        jpImagePopup.setBounds(132, 5, 155, 165);
        jpImagePopup.setVisible(false);

        jlblMItemType.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMItemType.setText("Type of Item");
        jpModifyItem.add(jlblMItemType);
        jlblMItemType.setBounds(10, 10, 130, 30);

        jlblMItemName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMItemName.setText("Item Name");
        jpModifyItem.add(jlblMItemName);
        jlblMItemName.setBounds(10, 50, 130, 30);

        jlblMPoint.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMPoint.setText("Point Required");
        jpModifyItem.add(jlblMPoint);
        jlblMPoint.setBounds(10, 90, 130, 30);

        jtfMItemName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpModifyItem.add(jtfMItemName);
        jtfMItemName.setBounds(140, 50, 290, 30);

        jspiMPoint.setModel(new javax.swing.SpinnerNumberModel(5, 5, 90, 5));
        jpModifyItem.add(jspiMPoint);
        jspiMPoint.setBounds(140, 90, 290, 30);

        jlblMValue.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMValue.setText("Value of Item");
        jpModifyItem.add(jlblMValue);
        jlblMValue.setBounds(10, 130, 130, 30);

        jspiMValue.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 99.0d, 1.0d));
        jpModifyItem.add(jspiMValue);
        jspiMValue.setBounds(140, 130, 290, 30);

        jbtRemove.setBackground(new java.awt.Color(39, 174, 96));
        jbtRemove.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtRemove.setForeground(new java.awt.Color(255, 255, 255));
        jbtRemove.setText("Remove");
        jbtRemove.setFocusPainted(false);
        jbtRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtRemoveActionPerformed(evt);
            }
        });
        jpModifyItem.add(jbtRemove);
        jbtRemove.setBounds(10, 220, 140, 50);

        jbtMSubmit.setBackground(new java.awt.Color(39, 174, 96));
        jbtMSubmit.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtMSubmit.setForeground(new java.awt.Color(255, 255, 255));
        jbtMSubmit.setText("Submit");
        jbtMSubmit.setFocusPainted(false);
        jbtMSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMSubmitActionPerformed(evt);
            }
        });
        jpModifyItem.add(jbtMSubmit);
        jbtMSubmit.setBounds(290, 220, 140, 50);

        jlblMImage.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMImage.setText("Item Image");
        jpModifyItem.add(jlblMImage);
        jlblMImage.setBounds(10, 170, 130, 30);

        jbtChooseAnother.setBackground(new java.awt.Color(39, 174, 96));
        jbtChooseAnother.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtChooseAnother.setForeground(new java.awt.Color(255, 255, 255));
        jbtChooseAnother.setText("Choose another");
        jbtChooseAnother.setEnabled(false);
        jbtChooseAnother.setFocusPainted(false);
        jbtChooseAnother.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtChooseAnotherActionPerformed(evt);
            }
        });
        jpModifyItem.add(jbtChooseAnother);
        jbtChooseAnother.setBounds(290, 170, 140, 30);

        jbtViewImage.setBackground(new java.awt.Color(39, 174, 96));
        jbtViewImage.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtViewImage.setForeground(new java.awt.Color(255, 255, 255));
        jbtViewImage.setText("View Image");
        jbtViewImage.setEnabled(false);
        jbtViewImage.setFocusPainted(false);
        jbtViewImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtViewImageActionPerformed(evt);
            }
        });
        jpModifyItem.add(jbtViewImage);
        jbtViewImage.setBounds(140, 170, 140, 30);

        jtfMItemType.setEditable(false);
        jtfMItemType.setBackground(new java.awt.Color(255, 255, 255));
        jtfMItemType.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jtfMItemType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfMItemTypeActionPerformed(evt);
            }
        });
        jpModifyItem.add(jtfMItemType);
        jtfMItemType.setBounds(140, 10, 290, 30);

        jpModifyItemCard.add(jpModifyItem);
        jpModifyItem.setBounds(0, 10, 445, 280);

        jpItemCard.add(jpModifyItemCard, "modifycard");

        jpRedeemCard.setBackground(new java.awt.Color(255, 255, 255));
        jpRedeemCard.setLayout(null);

        jpRedeemItemArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpRedeemItemArrowLayout = new javax.swing.GroupLayout(jpRedeemItemArrow);
        jpRedeemItemArrow.setLayout(jpRedeemItemArrowLayout);
        jpRedeemItemArrowLayout.setHorizontalGroup(
            jpRedeemItemArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 120, Short.MAX_VALUE)
        );
        jpRedeemItemArrowLayout.setVerticalGroup(
            jpRedeemItemArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpRedeemCard.add(jpRedeemItemArrow);
        jpRedeemItemArrow.setBounds(325, 0, 120, 10);

        jpRedeemItem.setBackground(new java.awt.Color(255, 255, 255));
        jpRedeemItem.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpRedeemItem.setLayout(null);

        javax.swing.GroupLayout jpScannerLayout = new javax.swing.GroupLayout(jpScanner);
        jpScanner.setLayout(jpScannerLayout);
        jpScannerLayout.setHorizontalGroup(
            jpScannerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
        jpScannerLayout.setVerticalGroup(
            jpScannerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 220, Short.MAX_VALUE)
        );

        jpRedeemItem.add(jpScanner);
        jpScanner.setBounds(80, 5, 300, 220);

        jlblScanResult.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpRedeemItem.add(jlblScanResult);
        jlblScanResult.setBounds(50, 230, 250, 40);

        jbtRedeem.setBackground(new java.awt.Color(39, 174, 96));
        jbtRedeem.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtRedeem.setForeground(new java.awt.Color(255, 255, 255));
        jbtRedeem.setText("Redeem?");
        jbtRedeem.setEnabled(false);
        jbtRedeem.setFocusPainted(false);
        jbtRedeem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtRedeemActionPerformed(evt);
            }
        });
        jpRedeemItem.add(jbtRedeem);
        jbtRedeem.setBounds(300, 230, 120, 40);

        jpRedeemCard.add(jpRedeemItem);
        jpRedeemItem.setBounds(0, 10, 445, 280);

        jpItemCard.add(jpRedeemCard, "redeemcard");

        jpItemContent.add(jpItemCard);
        jpItemCard.setBounds(5, 55, 445, 290);

        jpRedemption.add(jpItemContent);
        jpItemContent.setBounds(5, 5, 455, 350);

        add(jpRedemption);
        jpRedemption.setBounds(5, 10, 850, 360);
    }// </editor-fold>//GEN-END:initComponents

    private void jbtModifyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtModifyItemActionPerformed
        if (decoder != null) {
            decoder.closeWebCam();
        }
        jbtModifyItem.setBackground(new Color(142, 68, 173));
        jbtAddItem.setBackground(new Color(155, 89, 182));
        jbtRedeemItem.setBackground(new Color(155, 89, 182));
        if (jtbRedeemItem.getSelectedRow() >= 0) {
            cl.show(jpItemCard, "modifycard");
            jpImagePopup.setVisible(false);
            Object image = jtbRedeemItem.getModel().getValueAt(jtbRedeemItem.getSelectedRow(), 5);
            if (image != JSONObject.NULL) {
                jlblImage.setIcon(getImageFile(image.toString(), true));
                jbtViewImage.setEnabled(true);
            } else {
                jlblImage.setIcon(null);
                jbtViewImage.setEnabled(false);
            }
            jtfMItemType.setText(jtbRedeemItem.getValueAt(jtbRedeemItem.getSelectedRow(), 4).toString());
            if (jtfMItemType.getText().equals("Souvenir")) {
                isSouvenir = true;
                jbtChooseAnother.setEnabled(true);
            } else {
                jbtChooseAnother.setEnabled(false);
                isSouvenir = false;
            }
            itemCode = jtbRedeemItem.getValueAt(jtbRedeemItem.getSelectedRow(), 0).toString();
            jtfMItemName.setText(jtbRedeemItem.getValueAt(jtbRedeemItem.getSelectedRow(), 1).toString());
            jspiMPoint.setValue(Integer.parseInt(jtbRedeemItem.getValueAt(jtbRedeemItem.getSelectedRow(), 2).toString()));
            jspiMValue.setValue(Double.parseDouble(jtbRedeemItem.getValueAt(jtbRedeemItem.getSelectedRow(), 3).toString()));
        } else {
            Toast.makeText(this, "Please select from the table first.", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jbtModifyItemActionPerformed

    private void jbtAddItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAddItemActionPerformed
        if (decoder != null) {
            decoder.closeWebCam();
        }
        jbtModifyItem.setBackground(new Color(155, 89, 182));
        jbtAddItem.setBackground(new Color(142, 68, 173));
        jbtRedeemItem.setBackground(new Color(155, 89, 182));
        cl.show(jpItemCard, "addcard");
    }//GEN-LAST:event_jbtAddItemActionPerformed

    private void jbtAResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAResetActionPerformed
        jcbxAItemType.setSelectedIndex(0);
        jtfAItemName.setText(null);
        jtfImagePath.setText(null);
    }//GEN-LAST:event_jbtAResetActionPerformed

    private void jbtASubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtASubmitActionPerformed
        if (!jtfAItemName.getText().equals("")) {
            Map<String, Object> data = new HashMap<>();
            System.out.println(isSouvenir);
            if (isSouvenir) {
                data.putAll(imageData);
            }
            data.put("code", generateItemCode());
            data.put("name", jtfAItemName.getText());
            data.put("point", (Integer) jspiAPoint.getValue());
            data.put("value", (Double) jspiAValue.getValue());
            data.put("type", jcbxAItemType.getSelectedItem().toString());
            String result = RestServer.httpPost("redeemableitem", data);
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(getParent(), "New redeemable item added.", Toast.LENGTH_LONG).display();
                        populateTableData();
                    } else {
                        Toast.makeText(getParent(), "Unable to create new item now, please try again later.", Toast.LENGTH_LONG).display();
                    }
                } else {
                    Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                }
            } catch (JSONException ex) {
            }
        }else{
            Toast.makeText(getParent(), "Please fill in all fields first", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jbtASubmitActionPerformed

    private void jbtChooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtChooseActionPerformed
        int selected = jfcImageChooser.showOpenDialog(PointRedemptionPanel.this);
        if (selected == javax.swing.JFileChooser.APPROVE_OPTION) {
            jtfImagePath.setText(jfcImageChooser.getSelectedFile().getAbsolutePath());
            generateByteDataFromImageFile(jfcImageChooser.getSelectedFile());
        }
    }//GEN-LAST:event_jbtChooseActionPerformed

    private void jcbxAItemTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbxAItemTypeActionPerformed
        if (jcbxAItemType.getSelectedIndex() == jcbxAItemType.getItemCount() - 1) {
            String type = jcbxAItemType.getSelectedItem().toString();
            if (type.equals("Souvenir")) {
                isSouvenir = true;
            } else {
                isSouvenir = false;
            }
            jbtChoose.setEnabled(true);
        } else {
            jbtChoose.setEnabled(false);
        }
    }//GEN-LAST:event_jcbxAItemTypeActionPerformed

    private void jbtRedeemItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtRedeemItemActionPerformed
        if (decoder != null) {
            decoder.closeWebCam();
        }
        jbtModifyItem.setBackground(new Color(155, 89, 182));
        jbtAddItem.setBackground(new Color(155, 89, 182));
        jbtRedeemItem.setBackground(new Color(142, 68, 173));
        cl.show(jpItemCard, "redeemcard");
        jlblScanResult.setText(null);
        jbtRedeem.setEnabled(false);
        decoder = new QRDecoderPanel();
        jpScanner.add(decoder);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (decoder.isClosed()) {
                        if (!decoder.getDecodedID().equals("")) {
                            checkItemCode(decoder.getDecodedID());
                        }
                        break;
                    }
                }
            }
        }).start();
    }//GEN-LAST:event_jbtRedeemItemActionPerformed

    private void jbtRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtRemoveActionPerformed
        int option = JOptionPane.showConfirmDialog(this, "Are you sure you want to remove this item?", "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
        if (option == JOptionPane.YES_OPTION) {
            String result = RestServer.httpDelete("redeemableitem", itemCode);
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(this, "Item removed successfully.", Toast.LENGTH_SHORT).display();
                        populateTableData();
                    } else {
                        Toast.makeText(this, "Unable to remove item, please try again later.", Toast.LENGTH_SHORT).display();
                    }
                } else {
                    Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
            }
        }
    }//GEN-LAST:event_jbtRemoveActionPerformed

    private void jbtMSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMSubmitActionPerformed
        Map<String, Object> data = new HashMap<>();
        if (isSouvenir && imageData != null) {
            data.putAll(imageData);
        }
        data.put("name", jtfMItemName.getText());
        data.put("point", (Integer) jspiMPoint.getValue());
        data.put("value", (Double) jspiMValue.getValue());
        data.put("type", jtfMItemType.getText());
        String result = RestServer.httpPut("redeemableitem", data, itemCode);
        try {
            json = new JSONObject(result);
            boolean error = json.optBoolean("error");
            if (!error) {
                int statuscode = json.getInt("status");
                if (statuscode == 200) {
                    Toast.makeText(this, "Item updated successfully.", Toast.LENGTH_SHORT).display();
                    populateTableData();
                } else {
                    Toast.makeText(this, "Unable to update item, please try again later.", Toast.LENGTH_SHORT).display();
                }
            } else {
                Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
            }
        } catch (JSONException ex) {
        }
    }//GEN-LAST:event_jbtMSubmitActionPerformed

    private void jbtChooseAnotherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtChooseAnotherActionPerformed
        int selected = jfcImageChooser.showOpenDialog(PointRedemptionPanel.this);
        if (selected == javax.swing.JFileChooser.APPROVE_OPTION) {
            File selectedFile = jfcImageChooser.getSelectedFile();
            generateByteDataFromImageFile(selectedFile);
            jlblImage.setIcon(getImageFile(selectedFile.getAbsolutePath(), false));
            jbtViewImage.setEnabled(true);
        }
    }//GEN-LAST:event_jbtChooseAnotherActionPerformed

    private void jbtViewImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtViewImageActionPerformed
        if (!jpImagePopup.isVisible()) {
            jpImagePopup.setVisible(true);
        } else {
            jpImagePopup.setVisible(false);
        }
    }//GEN-LAST:event_jbtViewImageActionPerformed

    private void jtfMItemTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfMItemTypeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtfMItemTypeActionPerformed

    private void jbtRedeemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtRedeemActionPerformed
        Map<String, Object> data = new HashMap<>();
        data.put("status", "USED");
        String result = RestServer.httpPut("redeemeditem", data, refNo);
        try {
            json = new JSONObject(result);
            boolean error = json.optBoolean("error");
            if (!error) {
                int statuscode = json.getInt("status");
                if (statuscode == 200) {
                    Toast.makeText(this, "Item successfully redeemed.", Toast.LENGTH_SHORT).display();
                } else {
                    Toast.makeText(this, "Unable to redeem item, please try again later.", Toast.LENGTH_SHORT).display();
                }
            } else {
                Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
            }
        } catch (JSONException ex) {
        }
    }//GEN-LAST:event_jbtRedeemActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbtAReset;
    private javax.swing.JButton jbtASubmit;
    private javax.swing.JButton jbtAddItem;
    private javax.swing.JButton jbtChoose;
    private javax.swing.JButton jbtChooseAnother;
    private javax.swing.JButton jbtMSubmit;
    private javax.swing.JButton jbtModifyItem;
    private javax.swing.JButton jbtRedeem;
    private javax.swing.JButton jbtRedeemItem;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JButton jbtViewImage;
    private javax.swing.JComboBox jcbxAItemType;
    private javax.swing.JFileChooser jfcImageChooser;
    private javax.swing.JLabel jlblAImage;
    private javax.swing.JLabel jlblAItemName;
    private javax.swing.JLabel jlblAItemType;
    private javax.swing.JLabel jlblAPoint;
    private javax.swing.JLabel jlblAValue;
    private javax.swing.JLabel jlblImage;
    private javax.swing.JLabel jlblItems;
    private javax.swing.JLabel jlblMImage;
    private javax.swing.JLabel jlblMItemName;
    private javax.swing.JLabel jlblMItemType;
    private javax.swing.JLabel jlblMPoint;
    private javax.swing.JLabel jlblMValue;
    private javax.swing.JLabel jlblScanResult;
    private javax.swing.JPanel jpAddArrow;
    private javax.swing.JPanel jpAddItem;
    private javax.swing.JPanel jpAddItemArrow;
    private javax.swing.JPanel jpAddItemCard;
    private javax.swing.JPanel jpImage;
    private javax.swing.JPanel jpImagePopup;
    private javax.swing.JPanel jpImgArrow;
    private javax.swing.JPanel jpItemCard;
    private javax.swing.JPanel jpItemContent;
    private javax.swing.JPanel jpModifyItem;
    private javax.swing.JPanel jpModifyItemArrow;
    private javax.swing.JPanel jpModifyItemCard;
    private javax.swing.JPanel jpNullCard;
    private javax.swing.JPanel jpRedeemCard;
    private javax.swing.JPanel jpRedeemItem;
    private javax.swing.JPanel jpRedeemItemArrow;
    private javax.swing.JPanel jpRedemption;
    private javax.swing.JPanel jpScanner;
    private javax.swing.JScrollPane jspItemScroller;
    private javax.swing.JSpinner jspiAPoint;
    private javax.swing.JSpinner jspiAValue;
    private javax.swing.JSpinner jspiMPoint;
    private javax.swing.JSpinner jspiMValue;
    private javax.swing.JSeparator jsprItems;
    private javax.swing.JTable jtbRedeemItem;
    private javax.swing.JTextField jtfAItemName;
    private javax.swing.JTextField jtfImagePath;
    private javax.swing.JTextField jtfMItemName;
    private javax.swing.JTextField jtfMItemType;
    // End of variables declaration//GEN-END:variables
}
